﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using ZedGraph;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using Basic;
using SourceGrid;
namespace eCloudReport
{
    public partial class Form1 : Form
    {
        private PointPairList lst = new PointPairList();
        private string myProjectPath = "";
        private string ceProjectPath = "";
        private List<SaveVar> SaveList = new List<SaveVar>();//用来存储存储变量的
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            grid1.ColumnsCount = 6;
            grid1.FixedRows = 1;
            grid1.Rows.Insert(0);
            grid1[0, 0] = new SourceGrid.Cells.ColumnHeader("序号");
            grid1[0, 1] = new SourceGrid.Cells.ColumnHeader("名称");
            grid1[0, 2] = new SourceGrid.Cells.ColumnHeader("参数值");
            grid1[0, 3] = new SourceGrid.Cells.ColumnHeader("时间");
            grid1[0, 4] = new SourceGrid.Cells.ColumnHeader("类型");
            grid1[0, 5] = new SourceGrid.Cells.ColumnHeader("描述");
            grid1.Columns[0].Width = 80;
            grid1.Columns[1].Width = 100;
            grid1.Columns[2].Width = 100;
            grid1.Columns[3].Width = 150;
            grid1.Columns[4].Width = 100;
            grid1.Columns[5].Width = 255;
            textBox4.Text = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=iscada.mdb";
            DateTime t1 = new DateTime();
            t1 = DateTime.Now;
            textBox2.Text = t1.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss");
            DateTime t2 = new DateTime();
            t2 = DateTime.Now;
            textBox3.Text = t2.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss");
        }
        private void DelAll()
        {
            int rowsIndex = grid1.RowsCount;

            SourceGrid.RowInfo[] rows = new SourceGrid.RowInfo[rowsIndex - 1];
            for (int i = 0; i < rows.Length; i++)
                rows[i] = grid1.Rows[i + 1];

            foreach (SourceGrid.RowInfo r in rows)
                grid1.Rows.Remove(r.Index);

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!checkBox1.Checked && !checkBox3.Checked)
            {
                MessageBox.Show("请选择查询方式哦!");
                return;
            }
            if (checkBox1.Checked)
            {
                if (textBox1.Text == "")
                {
                    MessageBox.Show("请输入查询的名称哦!");
                    return;
                }
            }
            DelAll();
            /* selectCmd =
                 "SELECT * FROM SCORE WHERE 姓名 = '" +
                 selectName + "'";*/

            string connStr, selectCmd;
            connStr = textBox4.Text;
           // DateTime datemin = DateTime.Parse(textBox2.Text);
           // DateTime datemax = DateTime.Parse(textBox3.Text);
            selectCmd = "SELECT * FROM iscada where";
            //10
            if (checkBox1.Checked &&  !checkBox3.Checked)
            {
                selectCmd += " 名称 like '%" + textBox1.Text + "%'";
            }          
            //01
            if (!checkBox1.Checked  && checkBox3.Checked)
            {
                selectCmd += " 时间>= '" + textBox2.Text + "' " + " and 时间<= '" + textBox3.Text + "'";
               
            }
            //'11
            if (checkBox1.Checked &&  checkBox3.Checked)
            {
                selectCmd += " 名称 like '%" + textBox1.Text + "%'";
                selectCmd += " and 时间>= '" + textBox2.Text + "' " + " and 时间<= '" + textBox3.Text + "'";
            }
            selectCmd+= " order by 时间";
            OleDbConnection conn=null;
            OleDbCommand cmd;
            OleDbDataReader reader;
       
            try
            {    
                conn = new OleDbConnection(connStr);
                conn.Open();
                cmd = new OleDbCommand(selectCmd, conn);
                reader = cmd.ExecuteReader();
            }
            catch (Exception ee)
            {
                conn.Close();
                MessageBox.Show(ee.ToString());
                return;
            }
            DelAll();
          
            while (reader.Read())
            {

                int n = grid1.RowsCount;
                grid1.Rows.Insert(n);
                grid1[n, 0] = new SourceGrid.Cells.Cell(n.ToString(), typeof(string));
                grid1[n, 1] = new SourceGrid.Cells.Cell(reader["名称"], typeof(string));
                grid1[n, 2] = new SourceGrid.Cells.Cell(reader["参数值"], typeof(string));
                grid1[n, 3] = new SourceGrid.Cells.Cell(reader["时间"], typeof(string));
                grid1[n, 4] = new SourceGrid.Cells.Cell(reader["类型"], typeof(string));
                grid1[n, 5] = new SourceGrid.Cells.Cell(reader["描述"], typeof(string));
                //lst.Add((double)new XDate(DateTime.Parse(reader["时间"].ToString())), Convert.ToSingle(reader["参数值"]));

            }
            //grid1.AutoSizeCells();
            conn.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string connStr, selectCmd;
            connStr = textBox4.Text;
            selectCmd = "SELECT * FROM iscada";
            OleDbConnection conn;
            OleDbCommand cmd;
            OleDbDataReader reader;
            conn = new OleDbConnection(connStr);
            try
            {
                conn.Open();
                cmd = new OleDbCommand(selectCmd, conn);
                reader = cmd.ExecuteReader();
            }
            catch (Exception ee)
            {
                conn.Close();
                MessageBox.Show(ee.ToString());
                return;
            }
            DelAll();
            while (reader.Read())
            {

                int n = grid1.RowsCount;
                grid1.Rows.Insert(n);
                grid1[n, 0] = new SourceGrid.Cells.Cell(n.ToString(), typeof(string));
                grid1[n, 1] = new SourceGrid.Cells.Cell(reader["名称"], typeof(string));
                grid1[n, 2] = new SourceGrid.Cells.Cell(reader["参数值"], typeof(string));
                grid1[n, 3] = new SourceGrid.Cells.Cell(reader["时间"], typeof(string));
                grid1[n, 4] = new SourceGrid.Cells.Cell(reader["类型"], typeof(string));
                grid1[n, 5] = new SourceGrid.Cells.Cell(reader["描述"], typeof(string));


            }
            //grid1.AutoSizeCells();
            conn.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string l_Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "APMCFile.csv");

                using (System.IO.StreamWriter writer = new System.IO.StreamWriter(l_Path, false, System.Text.Encoding.Default))
                {
                    SourceGrid.Exporter.CSV csv = new SourceGrid.Exporter.CSV();
                    csv.Export(grid1, writer);
                    writer.Close();
                }

                DevAge.Shell.Utilities.OpenFile(l_Path);
            }
            catch (Exception err)
            {
                DevAge.Windows.Forms.ErrorDialog.Show(this, err, "APMC CSV Export Error!");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                string l_Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "APMCImageFile.bmp");

                SourceGrid.Exporter.Image image = new SourceGrid.Exporter.Image();

                using (System.Drawing.Bitmap bitmap = image.Export(grid1, grid1.CompleteRange))
                {
                    bitmap.Save(l_Path);
                }

                DevAge.Shell.Utilities.OpenFile(l_Path);
            }
            catch (Exception err)
            {
                DevAge.Windows.Forms.ErrorDialog.Show(this, err, "BITMAP Export Error!");
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                string l_Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "APMCHtml.htm");

                using (System.IO.FileStream l_Stream = new System.IO.FileStream(l_Path, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                {
                    SourceGrid.Exporter.HTML html = new SourceGrid.Exporter.HTML(SourceGrid.Exporter.ExportHTMLMode.Default, System.IO.Path.GetTempPath(), "", l_Stream);
                    html.Export(grid1);
                    l_Stream.Close();
                }

                DevAge.Shell.Utilities.OpenFile(l_Path);
            }
            catch (Exception err)
            {
                DevAge.Windows.Forms.ErrorDialog.Show(this, err, "HTML Export Error!");
            }
        }
        public void openTreeSolution()
        {
            //open sysinfo file
            string sMainPage="", sSQLCon="", sSaveTime="", sSaveHaveVar="NO";
            try
            {
                string systemfile = myProjectPath + "sysinfo" + ".sys";
                FileStream fs = new FileStream(systemfile, FileMode.Open);
                if (fs != null)
                {
                    StreamReader reader = new StreamReader(fs);
                    sMainPage = reader.ReadLine();
                    sSQLCon = reader.ReadLine();
                    sSaveTime = reader.ReadLine();
                    sSaveHaveVar = reader.ReadLine();
                    reader.Close();
                    fs.Close();
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("读取系统设置文件错误.");
                return;
            }
            if (sSaveHaveVar.Equals("YES"))
            {
                string db = myProjectPath + "SaveDB" + ".db";
                try
                {
                    FileStream fs = new FileStream(db, FileMode.Open);
                    XmlSerializer mySerializer = new XmlSerializer(typeof(List<SaveVar>));
                    SaveList = (List<SaveVar>)mySerializer.Deserialize(fs);
                    fs.Close();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                comboBox1.Items.Clear();
                textBox4.Text = sSQLCon;
                foreach (SaveVar var in SaveList)
                {
                    comboBox1.Items.Add(var.mName);
                }
            }
            else
            {
                MessageBox.Show("系统没有设置存储变量.");
            }
        }
        private void button6_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "cePrj Files (*.ecd)|*.ecd";
            openFileDialog1.InitialDirectory = "";
            openFileDialog1.Title = "打开工程文件";
            openFileDialog1.FileName = "";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                ceProjectPath = openFileDialog1.FileName;
                myProjectPath = new FileInfo(ceProjectPath).DirectoryName;
                myProjectPath = myProjectPath + "\\";
                //open solution tree
                try
                {            
                    openTreeSolution();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    this.Close();
                }
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请设置要生成曲线的变量名称");
                return;
            }
            lst.Clear();
            int n = grid1.RowsCount;
            for (int i = 1; i <n; i++)
            {
                CellContext[] context = new CellContext[grid1.Columns.Count];
                for (int c = 0; c < grid1.Columns.Count; c++)
                {
                    SourceGrid.Cells.ICellVirtual cell = grid1.GetCell(i, c);
                    Position pos = new Position(i, c);
                    context[c] = new CellContext(grid1, pos, cell);      
                }
                string s = context[1].DisplayText;
                string stype = context[4].DisplayText;
                stype = stype.TrimEnd();
                s = s.TrimEnd();
                if (s.Equals(textBox1.Text))
                {
                    string sv = context[2].DisplayText;
                    sv = sv.TrimEnd().ToUpper();
                    if (sv.Equals("ERROR"))
                    {
                        continue;
                    }
                    if (stype.Equals("Bit"))
                    {
                      
                        if (sv.Equals("FALSE") )
                        {
                            sv = "0";
                        }
                        if (sv.Equals("TRUE"))
                        {
                            sv = "1";
                        }
                        lst.Add((double)new XDate(DateTime.Parse(context[3].DisplayText)), Convert.ToByte(sv));
                    }
                    else if (stype.Equals("Float"))
                    {
                        lst.Add((double)new XDate(DateTime.Parse(context[3].DisplayText)), Convert.ToSingle(context[2].DisplayText));
                    }
                    else if (stype.Equals("Int16"))
                    {
                          lst.Add((double)new XDate(DateTime.Parse(context[3].DisplayText)), Convert.ToInt16(context[2].DisplayText));
                    }
                    else if (stype.Equals("Uint16"))
                    {
                        lst.Add((double)new XDate(DateTime.Parse(context[3].DisplayText)), Convert.ToUInt16(context[2].DisplayText));
                    }
                    else if (stype.Equals("Uint32"))
                    {
                        lst.Add((double)new XDate(DateTime.Parse(context[3].DisplayText)), Convert.ToUInt32(context[2].DisplayText));
                    }
                    else if (stype.Equals("Int32"))
                    {
                        lst.Add((double)new XDate(DateTime.Parse(context[3].DisplayText)), Convert.ToInt32(context[2].DisplayText));
                    }
                   
                }           
            }
            HistoryForm hform = new HistoryForm();
            hform.SetDataList(textBox1.Text,lst);
            hform.ShowDialog();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int n = this.comboBox1.SelectedIndex;
            if (n >= 0)
            {
                textBox1.Text = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
            }
        }

        private void comboBox1_DropDown(object sender, EventArgs e)
        {

        }




    }
}